package com.myapp.actions.user;

import com.myapp.entity.Role;
import com.myapp.entity.Uzer;
import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class AddUser implements WebAction {

  private Uzer user = new Uzer();

  @Override
  public void prepare(WebRequest request) throws WebException {
    user.setUsername(request.getStringNN("username"));
    user.setPassword(request.getStringNN("password"));
    user.setTimeZone(request.getStringNN("timeZone"));
    String[] roles = request.getStringsNN("role");
    for (String string : roles) {
      user.addRoles(Role.valueOf(string));
    }
    user.setDeleted(false);
  }

  @Override
    public EntityManager process(WebRequest req, WebResponse res, EntityManager em) throws Exception {
    em.persist(user);
    res.setMessage("Successfully added user");
    res.setResult(user);
    return em;
  }
}
